<?php

class AdminModule extends CWebModule
{
    private $allowCtl = array(
        'auth'
    );

	public function init()
	{
		// this method is called when the module is being created
		// you may place code here to customize the module or the application

		// import the module-level models and components
		$this->setImport(array(
			'admin.models.*',
			'admin.components.*',
		));
	}

	public function beforeControllerAction($controller, $action)
	{
	   $curr_ctl = Yii::app()->controller->id;
	   $session = Yii::app()->session;
	   if (!in_array($curr_ctl, $this->allowCtl) && (!isset($session['auth']) || empty($session['auth']))) {
	       $this->noLogin();
       }
       return true;
	}

	private function noLogin() {
	    if (Yii::app()->request->isAjaxRequest) {
	        $this->jsonResponse(array('code'=>2000,'message'=>'请先登录'));
        } else {
            $url = Yii::app()->createUrl('admin/auth/login');
            Yii::app()->getRequest()->redirect($url);
            exit;
        }
    }

    private function jsonResponse($data) {
        header('Content-Type:application/json; charset=utf-8');
        if (empty($data) || !is_array($data)) {
            $json = CJSON::encode(array());
        } else {
            $json = CJSON::encode($data);
        }
        exit($json);
    }
}
